package com.example.demo.Service;

import com.example.demo.mongo.Attention;
import com.example.demo.mongo.Follow;
import com.example.demo.mongo.UserDto;
import com.example.demo.mongo.dao.AttentionRepoistory;
import com.example.demo.mongo.dao.FollowRepoistory;
import com.example.demo.mongo.dao.UserRepoistory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author wujunyu
 * @date 2020/9/16 14:59
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepoistory userRepoistory;

    @Autowired
    private FollowRepoistory followRepoistory;

    @Autowired
    private AttentionRepoistory attentionRepoistory;

    @Override
    public Mono<List<UserDto>> findAll() {
        return userRepoistory.findAll().flatMap(user -> {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            Mono<List<String>> attentionId = attentionRepoistory.findAllByUserId(user.getUserId()).map(Attention::getAttentionId).collectList();
            Mono<List<String>> followId = followRepoistory.findAllByUserId(user.getUserId()).map(Follow::getFollowId).collectList();

            //下边两种写法效果一样
            return attentionId.zipWith(followId, (attention, follow) -> {
                userDto.setAttentionId(attention);
                userDto.setFollowId(follow);
                return userDto;
            });

            //如果逻辑较多，可以拆开写，步骤清晰一些
            /*Mono<UserDto> userDtoMono = attentionId.zipWith(followId, (attention, follow) -> {
                userDto.setAttentionId(attention);
                userDto.setFollowId(follow);
                return userDto;
            });
            return userDtoMono;*/

            //下边这种写法不行
            /*attentionId.zipWith(followId, (attention, follow) -> {
                userDto.setAttentionId(attention);
                userDto.setFollowId(follow);
                return userDto;
            });
            return Flux.just(userDto); // 直接这样写不管用，userDto没有进入到方法的逻辑中*/


        }).collectList();
    }
}
